from flask import Flask, render_template, request, redirect, url_for,jsonify
import json
import sqlite
import requests
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')  # 渲染模板文件

@app.route('/login', methods=['POST'])
def login():
    account = request.form['account']
    password = request.form['pswd']
    # 检查用户是否存在并验证密码
    response  = json.loads(sqlite.login(account, password))
    if response["code"] == 0:
        return redirect(url_for('home'))
    else:
        # 登录失败，返回错误信息
        error = "Invalid account or password."
        return render_template('index.html', error=error)

@app.route('/signup', methods=['POST'])
def signup():
    name = request.form['name']
    account = request.form['account']
    password = request.form['pswd']


    response = json.loads(sqlite.register(name, account, password))

    # 假设简单的注册流程，检查账户是否已存在

    if response["code"] == 0:
        # 注册成功，保存用户数据并显示成功信息
        success = "Registration successful! You can now log in."
        return render_template('home.html', success=success)

    else:
        if response["code"] == 404:
            error = "Account already exists!"
            return render_template('index.html', error=error)
        else:
            error = "Account already exists"
            return render_template('index.html', error=error)
@app.route('/home')
def home():
    return render_template('home.html')


@app.route('/pre_text', methods=['POST'])
def pre_text():
    try:
        # 获取JSON数据
        data = request.get_json()
        user_text = data.get('text')

        if not user_text:
            return jsonify({
                'status': 'error',
                'message': '文本内容不能为空'
            }), 400

        # 这里处理你的文本数据
        res_text = text_pre(user_text)
        res_json = json.loads(res_text)
        # 返回处理结果
        return jsonify({
            'status': 'success',
            'message': 'Ai: ' + '{:.2f}%'.format(res_json["data"]["ai"]*100) +', Human: ' + '{:.2f}%'.format(res_json["data"]["human"]*100),
            'data': res_text  # 或者返回处理后的数据
        })

    except Exception as e:
        # 处理可能的错误
        return jsonify({
            'status': 'error',
            'message': f'处理失败: {str(e)}'
        }), 500

def text_pre(text):
    data = {"text": text}
    print(data)
    response = requests.post("https://aidetector.tech/api/model/text-detector", json=data)
    print(response.json())
    return response.text

def img_pre(file):
    # 准备文件
    files = {
        "file": (
            "508022b8-76dc-4fa0-b678-017a9c67b571.jpg",  # 文件名
            open(file, "rb"),  # 文件内容
            "image/jpeg"  # 文件 MIME 类型
        )
    }

    # 发送请求
    response = requests.post("https://example.com/upload", files=files)

    # 输出响应
    print(response.status_code)
    print(response.text)


if __name__ == '__main__':
    app.run(host="0.0.0.0",debug=True)
